//
//  NetWorkVC.m
//  ConnectorDemo
//
//  Created by huck on 2020/9/14.
//  Copyright © 2020 huck. All rights reserved.
//

#import "HomeworkVC.h"
#import "UIRadioButton.h"

@interface HomeworkVC ()<UIDocumentPickerDelegate>

@property (nonatomic,strong) UITextField *numberTF;
@property (nonatomic,strong) UITextField *countTF;
@property (nonatomic, strong) UIRadioButton *radio;



@end

@implementation HomeworkVC


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"均值计算";
    [self setBtn1Name:@"刷新题目"];
    [self setBtn2Name:@"导出"];
    
    self.topViewHeight.constant = 120;
   
    [self.topView addSubview:self.radio];
    [self.radio mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(10);
        make.size.mas_equalTo(CGSizeMake(30, 30));
    }];
    
    WS(ws)
    UILabel *label = [[UILabel alloc] init];
    label.text = @"带括号";
    [self.topView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ws.radio.mas_right).with.offset(10);
        make.centerY.mas_equalTo(ws.radio.mas_centerY);
    }];
    
    [self.topView addSubview:self.numberTF];
    [self.numberTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(label.mas_right).with.offset(10);
        make.centerY.mas_equalTo(ws.radio.mas_centerY);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(100);
    }];
    
    [self.topView addSubview:self.countTF];
    [self.countTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(ws.radio.mas_centerY);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(100);
    }];
}

- (UIRadioButton *)radio {
    if (!_radio) {
        _radio = [[UIRadioButton alloc] initWithIcon:@"NotChoose" selectedIcon:@"Choose" clickBlock:^(UIButton *btn) {
        }];
    }
    return _radio;
}

- (UITextField *)numberTF {
    if (!_numberTF) {
        _numberTF = [[UITextField alloc] init];
        _numberTF.placeholder = @"多少以内加减法";
        _numberTF.text = @"20";
        _numberTF.backgroundColor = [UIColor whiteColor];
        _numberTF.borderStyle = UITextBorderStyleRoundedRect;
        _numberTF.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _numberTF;
}

-(UITextField *)countTF {
    if (!_countTF) {
        _countTF = [[UITextField alloc] init];
        _countTF.placeholder = @"题目数量";
        _countTF.text = @"92";
        _countTF.backgroundColor = [UIColor whiteColor];
        _countTF.borderStyle = UITextBorderStyleRoundedRect;
        _countTF.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _countTF;
}

- (void)clickBtn1 {
    NSInteger number = self.numberTF.text.integerValue;
    NSInteger count = self.countTF.text.integerValue;
    [self generalHomework:number count:count need:self.radio.isSelected];
}
    
- (void)clickBtn2 {
    NSString *filePath = [self filePath];
    if (![DYFileUtil exists:filePath]) {
        [self setInfo:@"文件还不存在"];
        return;
    }
    
    [self saveFile:filePath];
}

//[0,max]以内加减法 count题目数量 flag：要不要括号
-(void)generalHomework:(NSUInteger)maxNum count:(NSUInteger)count need:(BOOL)flag {
    NSMutableArray<NSNumber *> *numList = [NSMutableArray array];//保存每个数字，包括结果
    NSInteger numberCount = 3; //3个数计算,包括结果
    NSMutableString *result = [NSMutableString string];
    
    for (int i=1;i<=count;i++) {
        NSInteger min = 0;
        NSInteger max = maxNum;
        [numList removeAllObjects];
        NSInteger endResult = 0;
        NSInteger needIndex = -1;
        if (flag) {
            needIndex = [Util randomInt:numberCount-1];
        }
        
        for (int j=1;j<numberCount;j++) { //生成numberCount个数子
            NSInteger num1 = [Util randomInt:(max-min) offset:(min-0)];
            endResult += num1;
            [numList addObject:@(num1)];
            if (j<numberCount-1) {
                min = min - num1;
                max = max - num1;
            } else {
                [numList addObject:@(endResult)];
                //生成算式
                NSMutableString *str = [NSMutableString string];
                for (int k=0;k<numList.count;k++) {
                    if (k==0) {
                        if (needIndex == k ) {
                            [str appendFormat:@"(    )"];
                        } else {
                            [str appendFormat: @"%li%@",numList[k].integerValue,ABS(numList[k].integerValue) < 10 ? @" " : @""];
                        }
                    } else if (k==numList.count-1) {
                        [str appendFormat: @" = "];
                        if (needIndex == k ) {
                            [str appendFormat:@"(    )"];
                        } else if (flag){
                            [str appendFormat: @"%li%@",numList[k].integerValue,ABS(numList[k].integerValue) < 10 ? @" " : @""];
                        } else {
                            [str appendFormat:@"  "];
                        }
                    }else {
                        [str appendFormat: @" %@ ",numList[k].integerValue < 0 ? @"-" : @"+"];
                        if (needIndex == k ) {
                            [str appendFormat:@"(    )"];
                        } else {
                            [str appendFormat: @"%li%@",ABS(numList[k].integerValue),ABS(numList[k].integerValue) < 10 ? @" " : @""];
                        }
                    }
                }
                [result appendFormat:@"%@,",str];
                if (i%4==0) {
                    [result appendFormat:@"\n"];
                }
            }
            
        }
    }
    
    NSLog(@"%@",result);
    [self setInfo:result];
        
    //写入文件
    [result writeToFile:[self filePath]  atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
}

-(NSString *)filePath {
    NSString *strLogDirectory = [NSString stringWithFormat:@"%@%@%@",CACHES_DIR,@"/",@"homework"];
    [DYFileUtil mkdirs:strLogDirectory];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",strLogDirectory,@"homework.csv"];
    NSLog(@"filePath:%@",filePath);
    return filePath;
}


-(void)saveFile :(NSString *)configPath {
    
    UIDocumentPickerViewController *documentPickerVC = [[UIDocumentPickerViewController alloc] initForExportingURLs:@[[NSURL fileURLWithPath: configPath]] asCopy:YES];
    documentPickerVC.delegate = self;
    documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
    [self presentViewController:documentPickerVC animated:YES completion:nil];
}

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls
{
    // 获取授权
    BOOL fileAut = [urls.firstObject startAccessingSecurityScopedResource];
    if (fileAut) {
        // 通过文件协调工具来得到新的文件地址
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
            //文件存储成功
            if (error) {
                [self setInfo:@"下载失败"];
            } else {
                [self setInfo:@"导出成功"];
            }
        }];
        [urls.firstObject stopAccessingSecurityScopedResource];
    } else {
        //授权失败
        [self setInfo:@"下载授权失败"];
     }
}



@end
